package bestroomie.gui;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;

import bestroomie.util.CATAGORY_INDEX;
import bestroomie.util.DatePicker;
import bestroomie.db.*;
import bestroomie.entities.BRBill;
import bestroomie.entities.BRGroup;
import bestroomie.entities.BRUser;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

public class BRAddBillView extends javax.swing.JFrame {

	private ArrayList<BRUser> groupMembers;
	private BRUser creator;
	private BRGroup group;
	
    /**
     * Creates new form BRAddBillView
     */
    public BRAddBillView(ArrayList<BRUser> list,BRUser u,BRGroup g) {
    	this.groupMembers = list;
    	this.creator = u;
    	this.group = g;
        initComponents();
    }
    
    
   
    
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabelDate = new javax.swing.JLabel();
        jTextFieldDate = new javax.swing.JTextField();
        jLabelPayers = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        
        jLabelAmount = new javax.swing.JLabel();
        jTextFieldAmount = new javax.swing.JTextField();
        jLabelCatagory = new javax.swing.JLabel();
//        jScrollPane2 = new javax.swing.JScrollPane();
        
        jLabelDescription = new javax.swing.JLabel();
        jTextFieldDescription = new javax.swing.JTextField();
        jButtonAdd = new javax.swing.JButton();
        jButtonCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabelDate.setText("Date");

        jTextFieldDate.setText("");
        final JFrame f = this;
        jTextFieldDate.addMouseListener(new MouseAdapter(){
            @Override
            public void mouseClicked(MouseEvent e){
            	jTextFieldDate.setText(new DatePicker(f).setPickedDate());
            }
       });

        jLabelPayers.setText("Payers");
        
        
        
       
        DefaultListModel listModel = new DefaultListModel();
        
        listModel.clear();
        for(int i=0; i<this.groupMembers.size(); i++)  
        {  
        	BRUser u = this.groupMembers.get(i);
        	listModel.addElement(u.getUserName());
        }  
        
        
        
        
        jListPayers = new javax.swing.JList(listModel);
        
        
        
        
        
        
        
        jScrollPane1.setViewportView(jListPayers);

        jLabelAmount.setText("Amount");

        jTextFieldAmount.setText("0.0");

        jLabelCatagory.setText("Catagory");
        
        
        DefaultComboBoxModel comboModel = new DefaultComboBoxModel();
        for(CATAGORY_INDEX i : CATAGORY_INDEX.values()) {
        	comboModel.addElement(CATAGORY_INDEX.getCatagoryString(i));
        }
        
        
        jComboCatagory = new javax.swing.JComboBox(comboModel);
        
        

        jLabelDescription.setText("Description");

        jTextFieldDescription.setText("");

        jButtonAdd.setText("Add");
        jButtonAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAddActionPerformed(evt);
            }
        });

        jButtonCancel.setText("Cancel");
        jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(77, 77, 77)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabelDate)
                            .addComponent(jLabelPayers)
                            .addComponent(jLabelAmount)
                            .addComponent(jLabelCatagory)
                            .addComponent(jLabelDescription))
                        .addGap(52, 52, 52)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jTextFieldDate)
                            .addComponent(jScrollPane1)
                            .addComponent(jTextFieldAmount)
                            .addComponent(jComboCatagory)
                            .addComponent(jTextFieldDescription, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(117, 117, 117)
                        .addComponent(jButtonAdd)
                        .addGap(43, 43, 43)
                        .addComponent(jButtonCancel)))
                .addContainerGap(78, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelDate)
                    .addComponent(jTextFieldDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelPayers)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelAmount)
                    .addComponent(jTextFieldAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelCatagory)
                    .addComponent(jComboCatagory, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelDescription)
                    .addComponent(jTextFieldDescription, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonAdd)
                    .addComponent(jButtonCancel))
                .addGap(35, 35, 35))
        );

        pack();
    }// </editor-fold>                        

    private void jButtonAddActionPerformed(java.awt.event.ActionEvent evt) {      
    	
    	//this.jComboCatagory.get
    	System.out.println("The selected index jComboCatagory is " + this.jComboCatagory.getSelectedIndex());
    	System.out.println("The selected # of jListPayers  is " + this.jListPayers.getSelectedValuesList().size());
    	
    	
    	Float total_amount = Float.parseFloat(this.jTextFieldAmount.getText().trim());
    	Float amount_share = total_amount / (this.jListPayers.getSelectedValuesList().size() + 1);
    	
    	/**
    	 *  private String transId;
			private String createrUser;
			private String group;
			private CATAGORY_INDEX catagory; 
			private String date;
			private String[] payerList;
			private float[] amountList; 
			private boolean[] approvalList;
			private boolean[] paidList;
			private String description;
			private float total_amount;
    	 * **/
    	
    	BRBill b = new BRBill();
    	b.setCreateUser(this.creator.getUserEmail());
    	float f[] = new float[this.jListPayers.getSelectedValuesList().size()];
    	for(int i=0;i<f.length;i++)
    		f[i] = amount_share;
    	b.setAmntList(f);
    	b.setGroup(this.group.getGroupId());
    	b.setCatagory(CATAGORY_INDEX.fromInteger(this.jComboCatagory.getSelectedIndex()));
    	b.setDate(this.jTextFieldDate.getText());
    	
    	String tmpStr[] = new String[this.jListPayers.getSelectedValuesList().size()];
    	boolean tmpBool[] = new boolean[this.jListPayers.getSelectedValuesList().size()];
    	boolean tmpBool1[] = new boolean[this.jListPayers.getSelectedValuesList().size()];
//    	List<String> tmpIndexList = this.jListPayers.getSelectedValuesList();
    	int indices[] = this.jListPayers.getSelectedIndices();
    	for(int i=0;i<indices.length;i++) {
    		tmpStr[i] = this.groupMembers.get(indices[i]).getUserEmail();
    		tmpBool[i] = false;
    		tmpBool1[i] = false;
    	}
    	b.setPayerList(tmpStr);
    	b.setApprovalList(tmpBool);
    	b.setPaidList(tmpBool1);
    	b.setTotal_amount(Float.parseFloat(this.jTextFieldAmount.getText().trim()));
    	b.setDescription(this.jTextFieldDescription.getText().trim());
    	
    	
    	
    	b.addNewBill(this.creator.getUserEmail());
    	
    	this.dispose();
    	this.setVisible(false);
    	
    	
    	//b.addNewBill(this.creator.getUserEmail());
        // TODO add your handling code here:
    }                                          

    private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {                                              
        // TODO add your handling code here:
        this.dispose();
        this.setVisible(false);
    }                                             

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BRAddBillView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BRAddBillView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BRAddBillView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BRAddBillView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//            	BRGroup g = new BRGroup("group1");
//            	g.load();
//                new BRAddBillView(g.get).setVisible(true);
//            }
//        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButtonAdd;
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JLabel jLabelAmount;
    private javax.swing.JLabel jLabelCatagory;
    private javax.swing.JLabel jLabelDate;
    private javax.swing.JLabel jLabelDescription;
    private javax.swing.JLabel jLabelPayers;
    private javax.swing.JComboBox<String> jComboCatagory;
    private javax.swing.JList jListPayers;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextFieldAmount;
    private javax.swing.JTextField jTextFieldDate;
    private javax.swing.JTextField jTextFieldDescription;
    // End of variables declaration                   
}
